<template>
  <div class="hm-user">
    <!-- 用户信息区域 -->
    <div class="user-info">
      <div class="avatar">
        <img :src="userInfo.avatar" alt="avatar" />
      </div>
      <div class="username">{{ userInfo.username }}</div>
    </div>

    <!-- 数据统计区域 -->
    <div class="user-stats">
      <div class="stat-item" @click="go('article')">
        <van-icon name="clock-o" />
        <span>历史记录</span>
      </div>
      <div class="stat-item" @click="go('collect')">
        <van-icon name="star-o" />
        <span>我的收藏</span>
      </div>
      <div class="stat-item" @click="go('like')">
        <van-icon name="good-job-o" />
        <span>我的点赞</span>
      </div>
    </div>
    <div class="user-list">
      <van-cell-group>
        <van-cell title="推荐分享" is-link />
        <van-cell title="意见反馈" is-link />
        <van-cell title="关于我们" is-link />
        <van-cell title="退出登录" is-link @click="logout" />
      </van-cell-group>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      userInfo: {},
    };
  },
  created() {
    this.getUser();
  },
  methods: {
    go(path) {
      this.$router.push(`/index/${path}`);
    },
    async getUser() {
      //http://interview-api-t.itheima.net/h5/user/currentUser 携带token
      const res = await axios.get(
        "http://interview-api-t.itheima.net/h5/user/currentUser",
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      this.userInfo = res.data.data;
    },
    async logout() {
      //http://interview-api-t.itheima.net/h5/user/logout 携带token
      try {
        await axios.get("http://interview-api-t.itheima.net/h5/user/logout", {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        });
        localStorage.removeItem("token");
        this.$router.push("/login");
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.hm-user {
  background-color: #f5f5f5;
  height: 89.5vh;
  padding: 10px;
  .user-info {
    padding: 20px;

    display: flex;
    align-items: center;

    .avatar {
      width: 21.33vw;
      height: 21.33vw;
      border-radius: 50%;
      overflow: hidden;
      margin-right: 15px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .username {
      font-size: 4.8vw;
      font-weight: bold;
    }
  }

  .user-stats {
    background: #fff;
    display: flex;
    padding: 15px 0;
    margin: 1px 0 20px;
    .stat-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;

      .van-icon {
        font-size: 24px;
        margin-bottom: 5px;
      }

      span {
        font-size: 14px;
        color: #666;
      }
    }
  }
}
</style>
